// components/arraySelector/arraySelector.js
import * as API_Dict from '../../api/dict'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    selectCount: { //最多选择多少个
      type: Number,
      value: 100
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    serviceName:'',
    serviceItemDic:[],//读取数据字典

  },

  /**
   * 组件的方法列表
   */
  methods: {

    //加载组件值
    loadDic(e){
      let that = this
      API_Dict.getDictData(e.key).then(res =>{
        this.setData({
          serviceItemDic:res,
          serviceName:e.title
        })
        //当有被选中的值的时候
        if(e.selected){
          //已选项
          let selectedArr = JSON.parse(e.selected)
          let serviceItemDic=res;
          //可选项
          for(var i = 0; i < serviceItemDic.length; i++){
            for(var j = 0; j < selectedArr.length; j++){
              if(serviceItemDic[i].dictValue == selectedArr[j].dictValue){
                let jso=serviceItemDic[i];
                let selected=false;
                if(!jso.selected){
                  selected=true;
                }
                jso.selected=true;
                serviceItemDic[i]=jso
              }
            }
          }
          this.setData({serviceItemDic:serviceItemDic});
        }
      })
    },
      check(value){
        return value.selected
      },
    selectServiceItemDic:function(e){
      let that = this
      if(0 == that.data.selectCount){
        return
      }
      const index= e.currentTarget.dataset.index;
      let serviceItemDic=this.data.serviceItemDic;
      let jso=serviceItemDic[index];
      let selected=false;
      if(!jso.selected){
        selected=true;
      }
      jso.selected=selected;
      serviceItemDic[index]=jso
      var selectArr = serviceItemDic.filter(this.check)
      if(selectArr.length > this.data.selectCount){
          wx.showToast({
            title: '最多选择'+that.data.selectCount+'个',
            icon:'none'
          })
          return
      }
      this.setData({serviceItemDic:serviceItemDic});
      let result = []
      //回调给上层
      for(var i = 0; i<selectArr.length; i++){
        const {dictLabel,dictValue} = selectArr[i]
        let item = {dictLabel:dictLabel,dictValue:dictValue}
        result.push(item)
      }
      var data = {
        data: result
      }
      this.triggerEvent('select', data, {})
    },
  }
})
